package com.happy016.config;

import com.happy016.entity.AjaxResult;
import com.happy016.exception.AjaxException;
import com.happy016.exception.ViewException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 注解@ControllerAdvice,spring3.2之后就有的
 * 主要作用是:
 *      把@ExceptionHandler @InitBinder @ModelAttribute这三个注解的方法,应用到 @RequestMapping
 * @author Linyb
 * create on 2017/8/17 12:15
 */
@ControllerAdvice
//@RestControllerAdvice
//异步,点进去看源码可以看到 这个注解引用了@ControllerAdvice,里面多了个@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = AjaxException.class)
    @ResponseBody
    public AjaxResult jsonErrorHandler(HttpServletRequest request, AjaxException e){
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setMessage(e.getMessage());
        ajaxResult.setUrl(request.getRequestURL().toString());
        //这里还可以做一些其它操作,比如可以把异常信息存表,做记录
        return ajaxResult;
    }

    @ExceptionHandler(value = ViewException.class)
    public ModelAndView viewErrorHandler(HttpServletRequest request, ViewException e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception",e);
        modelAndView.setViewName("exception/error"); //返回error页面
        modelAndView.addObject("url",request.getRequestURL().toString());
        //这里还可以做一些其它操作,比如可以把异常信息存表,做记录
        return modelAndView;
    }

}
